<?php
/**
 * @package orinoco.framework
 * @subpackage application
 * @author Ryan Yonzon <rawswift@gmail.com>
 * @copyright Copyright 2008-2009 Ryan Yonzon 
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * view/template helper
 */
class View {

	/**
	 * redirect page then terminate
	 *
	 * @param string $_action action/page where to redirect
	 * @param string $_controller controller/page to redirect
	 * @param array $_additional_parameters additional parameters, e.g. ?id=1&name=foo&add=bar
	 * @param int $_time_interval time/seconds before redirect
	 */
	public function redirect_to($_action = NULL, $_controller = NULL, $_additional_parameters = NULL, $_time_interval = 0) {
	
		// controller
		if(isset($_controller) && $_controller != '') {
			$_to_controller = $_controller;
		} else {
			// get current controller
			$_to_controller = $this->_controller;
		}					

		if(USE_TRAILING_SLASH) {
			$_to_controller = $_to_controller . '/';
		}
		
		// method
		$_add_param = NULL;		
		if(isset($_action) && $_action != '') {
				if(USE_TRAILING_SLASH) {
					$_to_action = $_action;					
					$_to_action = $_to_action . '/';
				} else {
					$_to_action = '/' . $_action;
				}

				// additional parameters
				if(isset($_additional_parameters)) {
					$_add_param = '?';
					foreach($_additional_parameters as $_k => $_v) {
						$_add_param = $_add_param . $_k . '=' . $_v . '&';
					}		
					// remove trailing "&"
					$_add_param[strlen($_add_param) - 1] = '';
					$_add_param = trim($_add_param);
				}
			
		} else {
			$_to_action = NULL;			
		}
		
		$_redirect = '<meta http-equiv="Refresh" content="' . $_time_interval . '; URL=/' . $_to_controller . $_to_action . $_add_param . '">';

		// let it boggie!
		print $_redirect;
		exit(0);
	}
	
	/**
	 * explicitly use other view/template instead of the associated view/template
	 *
	 * @param string $_action view/action template to use
	 * @param string $_controller view/controller template to use
	 * @return true if file exist else throw an exception
	 */
	public function use_template($_action, $_controller = NULL) {
		// controller
		if(isset($_controller) && $_controller != '') {
			$_controller_of = $_controller;
		} else {
			// get current controller
			$_controller_of = $this->_controller;
		}					
		
			$_view_path = APPLICATION_DIR . $this->_application . '/' . CONTENT_DIR . $_controller_of . '/' . $_action . VIEW_FILE_SUFFIX . VIEW_FILE_EXTENSION;

			// check if view file exists
			if(!file_exists($_view_path)) {
				throw new Exception('Template "' . $_view_path . '" does not exists.');
			}
				$this->__view = $_view_path;
				return true;	
	}
	
	/**
	 * print an array
	 *
	 * @param array $_arr array to print
	 */
	public function debug_array($_arr) {
		echo '<pre>';
		print_r($_arr);
		echo '</pre>';		
	}	

} // end class

// -EOF-